package com.zdy.im.tio.command.handler;

import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.tio.TioServerConfig;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.packets.HeartbeatResponseVo;
import com.zdy.im.tio.packets.SocketResponseVo;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.Opcode;
import org.tio.websocket.common.WsResponse;

import java.io.UnsupportedEncodingException;


/**
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档",group = "SOCKET-GROUP")
public class HeartbeatRequestHandler extends AbstractCommandHandler
{
	@Override
	public Command command() {
		return Command.COMMAND_HEARTBEAT_REQ;
	}

	@ApiDoc(
			cmd = "13",methodType = "ws",
			value = "心跳协议 cmd=13",
			request = Object.class,
			response = boolean.class
	)
	@Override
	public Packet handler(Packet packet, ChannelContext channelContext) throws ImException
	{
		SocketResponseVo heartbeatBody = new SocketResponseVo(Command.COMMAND_HEARTBEAT_REQ)
				.setCode(0)
				.setData(new HeartbeatResponseVo(Protocol.HEARTBEAT_BYTE));

		String json = JsonUtils.toJson(heartbeatBody);
		Packet heartbeatPacket =  this.converterHeartbeatResponse(json);
		WsResponse wsResponse = WsResponse.fromText(Opcode.PONG.name(),TioServerConfig.CHARSET);
		Tio.send(channelContext, wsResponse);
		return heartbeatPacket;
	}



	public WsResponse converterHeartbeatResponse(String response){
		WsResponse wsResponse = new WsResponse();
		try {
			wsResponse.setBody(response.getBytes(TioServerConfig.CHARSET));
		} catch (UnsupportedEncodingException e) {
		}
		wsResponse.setWsOpcode(Opcode.PONG);

		return wsResponse;
	}
}
